package loja.gui;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import loja.dao.ClienteDao;
import loja.dao.exceptions.BuscaException;
import loja.dominio.Cliente;
import loja.gui.tablemodel.ClienteTableModel;
import loja.gui.utils.EstadoInterface;

import loja.gui.utils.MessageUtil;
import loja.validacao.ClienteValidador;
import loja.validacao.Validador;

/**
 *
 * @author Rodrigo
 */
public class ClienteForm extends javax.swing.JFrame {

    private EstadoInterface inicial;
    private EstadoInterface emAdicao;
    private EstadoInterface emEdicao;
    private EstadoInterface emPesquisa;
    private Cliente cliente;
    private ClienteDao clienteDao;
    private ClienteTableModel model;
    private List<Cliente> cadClientes;

    public ClienteForm() {
        try {
            model = new ClienteTableModel();
            clienteDao = new ClienteDao();
            initComponents();
            initEstados();
            inicial.mudaParaEstado();
            model.limpar();

        } catch (Exception ex) {
            MessageUtil.errorMessage(this, ex.getMessage());
        }
    }

    private void initEstados() {

        inicial = new EstadoInterface();
        emAdicao = new EstadoInterface();
        emEdicao = new EstadoInterface();
        emPesquisa = new EstadoInterface();

        //Estado inicial
        //habilitados
        inicial.adicionaHabilitado(txtPesquisar);
        inicial.adicionaHabilitado(btnPesquisar);
        inicial.adicionaHabilitado(btnNovo);
        inicial.adicionaHabilitado(btnSair);

        //desabilitados
        inicial.adicionaDesabilitado(btnCancelar);
        inicial.adicionaDesabilitado(btnExcluir);
        inicial.adicionaDesabilitado(btnSalvar);
        inicial.adicionaDesabilitado(txtId);
        inicial.adicionaDesabilitado(txtCliente);
        inicial.adicionaDesabilitado(txtEndereco);
        inicial.adicionaDesabilitado(txtNascimento);
        inicial.adicionaDesabilitado(txtCpf);
        inicial.adicionaDesabilitado(txtEmail);
        inicial.adicionaDesabilitado(tabelaClientes);

        //semtexto
        inicial.adicionarSemTexto(txtId);
        inicial.adicionarSemTexto(txtCliente);
        inicial.adicionarSemTexto(txtEndereco);
        inicial.adicionarSemTexto(txtNascimento);
        inicial.adicionarSemTexto(txtCpf);
        inicial.adicionarSemTexto(txtEmail);


        //Estado em adição
        //habilitados

        emAdicao.adicionaHabilitado(btnSalvar);
        emAdicao.adicionaHabilitado(btnSair);
        emAdicao.adicionaHabilitado(btnCancelar);
        emAdicao.adicionaHabilitado(txtCliente);
        emAdicao.adicionaHabilitado(txtEndereco);
        emAdicao.adicionaHabilitado(txtNascimento);
        emAdicao.adicionaHabilitado(txtCpf);
        emAdicao.adicionaHabilitado(txtEmail);

        //desabilitados
        emAdicao.adicionaDesabilitado(btnNovo);
        emAdicao.adicionaDesabilitado(btnExcluir);
        emAdicao.adicionaDesabilitado(btnPesquisar);
        emAdicao.adicionaDesabilitado(txtPesquisar);
        emAdicao.adicionaDesabilitado(txtId);
        emAdicao.adicionaDesabilitado(tabelaClientes);

        //semtexto
        emAdicao.adicionarSemTexto(txtId);
        emAdicao.adicionarSemTexto(txtCliente);
        emAdicao.adicionarSemTexto(txtEndereco);
        emAdicao.adicionarSemTexto(txtNascimento);
        emAdicao.adicionarSemTexto(txtCpf);
        emAdicao.adicionarSemTexto(txtEmail);

        //estado em edição
        //habilitados
        emEdicao.adicionaHabilitado(btnPesquisar);
        emEdicao.adicionaHabilitado(btnCancelar);
        emEdicao.adicionaHabilitado(btnExcluir);
        emEdicao.adicionaHabilitado(btnSair);
        emEdicao.adicionaHabilitado(btnSalvar);
        emEdicao.adicionaHabilitado(txtCliente);
        emEdicao.adicionaHabilitado(txtEndereco);
        emEdicao.adicionaHabilitado(txtNascimento);
        emEdicao.adicionaHabilitado(txtCpf);
        emEdicao.adicionaHabilitado(txtEmail);

        //desabilitados
        emEdicao.adicionaDesabilitado(btnNovo);
        emEdicao.adicionaDesabilitado(txtPesquisar);
        emEdicao.adicionaDesabilitado(btnPesquisar);
        emEdicao.adicionaDesabilitado(txtId);

        //estado em pesquisa
        //habilitados
        emPesquisa.adicionaHabilitado(txtPesquisar);
        emPesquisa.adicionaHabilitado(btnPesquisar);
        emPesquisa.adicionaHabilitado(btnNovo);
        emPesquisa.adicionaHabilitado(btnSair);
        emPesquisa.adicionaHabilitado(btnCancelar);
        emPesquisa.adicionaHabilitado(tabelaClientes);

        //desabilitados
        emPesquisa.adicionaDesabilitado(btnExcluir);
        emPesquisa.adicionaDesabilitado(btnSalvar);
        emPesquisa.adicionaDesabilitado(txtId);
        emPesquisa.adicionaDesabilitado(txtCliente);
        emPesquisa.adicionaDesabilitado(txtEndereco);
        emPesquisa.adicionaDesabilitado(txtNascimento);
        emPesquisa.adicionaDesabilitado(txtCpf);
        emPesquisa.adicionaDesabilitado(txtEmail);


        //semtexto
        emPesquisa.adicionarSemTexto(txtId);
        emPesquisa.adicionarSemTexto(txtCliente);
        emPesquisa.adicionarSemTexto(txtEndereco);
        emPesquisa.adicionarSemTexto(txtNascimento);
        emPesquisa.adicionarSemTexto(txtCpf);
        emPesquisa.adicionarSemTexto(txtEmail);
    }

    private void resetaEstados() {
        inicial.reset();
        emAdicao.reset();
        emEdicao.reset();
        emPesquisa.reset();
    }

    private void preencherClienteComCampos() {
        cliente.setNome(txtCliente.getText());
        cliente.setEndereco(txtEndereco.getText());
        cliente.setNascimento(txtNascimento.getText());
        cliente.setCpf(txtCpf.getText());
        cliente.setEmail(txtEmail.getText());

    }

    private Map getMapaDeAtributos() {
        Map map = new HashMap();

        map.put("cliente", txtCliente.getText());
        map.put("endereco", txtEndereco.getText());
        map.put("nascimento", txtNascimento.getText());
        map.put("cpf", txtCpf.getText());
        map.put("email", txtEmail.getText());
        return map;

    }

    private void listarClientes() throws SQLException, BuscaException {
        ClienteDao dao = new ClienteDao();
        cadClientes = dao.buscarPorDescricao(txtPesquisar.getText());
        model.setCadCategorias(cadClientes);
    }

    private void preencheCamposComCliente() {
        txtId.setText("" + cliente.getId());
        txtCliente.setText("" + cliente.getNome());
        txtEndereco.setText("" + cliente.getEndereco());
        txtNascimento.setText("" + cliente.getNascimento());
        txtCpf.setText("" + cliente.getCpf());
        txtEmail.setText("" + cliente.getEmail());

    }

    private boolean validaCpf(String cpfCliente) throws BuscaException {
        boolean eValido = true;
        //ClienteDao clienteDao = new ClienteDao();

        System.out.println("CPF " + cpfCliente.toUpperCase());
        Cliente c = clienteDao.buscarPorCpf(cpfCliente);
        if (c != null) {
            eValido = false;
        }
        return eValido;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        PainelCliente = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtId = new javax.swing.JTextField();
        txtEndereco = new javax.swing.JTextField();
        txtEmail = new javax.swing.JTextField();
        txtCliente = new javax.swing.JTextField();
        txtNascimento = new javax.swing.JFormattedTextField();
        txtCpf = new javax.swing.JFormattedTextField();
        lblMensagem = new javax.swing.JLabel();
        PainelPesquisar = new javax.swing.JPanel();
        btnPesquisar = new javax.swing.JButton();
        txtPesquisar = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabelaClientes = new javax.swing.JTable();
        PainelButao = new javax.swing.JPanel();
        btnNovo = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        btnSalvar = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastro de Clientes");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setLocationByPlatform(true);

        PainelCliente.setBorder(javax.swing.BorderFactory.createTitledBorder("Cadastro de Clientes"));

        jLabel1.setText("Codigo:");

        jLabel2.setText("Nome:");

        jLabel3.setText("Endereço:");

        jLabel4.setText("Data/ Nasc.:");

        jLabel5.setText("CPF:");

        jLabel6.setText("E-Mail:");

        txtCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtClienteActionPerformed(evt);
            }
        });

        try {
            txtNascimento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtNascimento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtNascimentoActionPerformed(evt);
            }
        });
        txtNascimento.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                txtNascimentoPropertyChange(evt);
            }
        });

        try {
            txtCpf.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        javax.swing.GroupLayout PainelClienteLayout = new javax.swing.GroupLayout(PainelCliente);
        PainelCliente.setLayout(PainelClienteLayout);
        PainelClienteLayout.setHorizontalGroup(
            PainelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PainelClienteLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(PainelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addGap(6, 6, 6)
                .addGroup(PainelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtEndereco, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
                    .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtCliente))
                .addGap(18, 18, 18)
                .addGroup(PainelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(PainelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtEmail, javax.swing.GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE)
                    .addComponent(txtNascimento, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(18, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PainelClienteLayout.createSequentialGroup()
                .addContainerGap(181, Short.MAX_VALUE)
                .addComponent(lblMensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(71, 71, 71))
        );
        PainelClienteLayout.setVerticalGroup(
            PainelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PainelClienteLayout.createSequentialGroup()
                .addComponent(lblMensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(PainelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(PainelClienteLayout.createSequentialGroup()
                        .addGroup(PainelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(txtNascimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(PainelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(txtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(PainelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(PainelClienteLayout.createSequentialGroup()
                        .addGroup(PainelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(PainelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(PainelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(txtEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        PainelPesquisar.setBorder(javax.swing.BorderFactory.createTitledBorder("Pesquisa de Clientes"));

        btnPesquisar.setText("Pesquisar");
        btnPesquisar.setToolTipText("Pesquisa de cadastro");
        btnPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPesquisarActionPerformed(evt);
            }
        });

        txtPesquisar.setToolTipText("Digite o nome do Cliente no qual quer pesquisar.");

        javax.swing.GroupLayout PainelPesquisarLayout = new javax.swing.GroupLayout(PainelPesquisar);
        PainelPesquisar.setLayout(PainelPesquisarLayout);
        PainelPesquisarLayout.setHorizontalGroup(
            PainelPesquisarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PainelPesquisarLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtPesquisar, javax.swing.GroupLayout.DEFAULT_SIZE, 535, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnPesquisar))
        );
        PainelPesquisarLayout.setVerticalGroup(
            PainelPesquisarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PainelPesquisarLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(PainelPesquisarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnPesquisar)
                    .addComponent(txtPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        tabelaClientes.setAutoCreateRowSorter(true);
        tabelaClientes.setModel(model);
        tabelaClientes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaClientesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabelaClientes);

        btnNovo.setText("Novo");
        btnNovo.setToolTipText("Novo cadastro");
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.setToolTipText("Alterar dados do cadastro");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnExcluir.setText("Excluir");
        btnExcluir.setToolTipText("Excluir Cadastro");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        btnSalvar.setText("Salvar");
        btnSalvar.setToolTipText("Salvar Cadastro");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnSair.setText("Sair");
        btnSair.setToolTipText("Sair da tela de cadastro");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout PainelButaoLayout = new javax.swing.GroupLayout(PainelButao);
        PainelButao.setLayout(PainelButaoLayout);
        PainelButaoLayout.setHorizontalGroup(
            PainelButaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PainelButaoLayout.createSequentialGroup()
                .addGap(113, 113, 113)
                .addComponent(btnNovo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnCancelar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnExcluir)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnSalvar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnSair)
                .addContainerGap(114, Short.MAX_VALUE))
        );

        PainelButaoLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnCancelar, btnExcluir, btnNovo, btnSair, btnSalvar});

        PainelButaoLayout.setVerticalGroup(
            PainelButaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PainelButaoLayout.createSequentialGroup()
                .addContainerGap(21, Short.MAX_VALUE)
                .addGroup(PainelButaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNovo)
                    .addComponent(btnCancelar)
                    .addComponent(btnExcluir)
                    .addComponent(btnSalvar)
                    .addComponent(btnSair)))
        );

        PainelButaoLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnCancelar, btnExcluir, btnNovo, btnSair, btnSalvar});

        btnNovo.getAccessibleContext().setAccessibleDescription(null);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE)
                    .addComponent(PainelPesquisar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(PainelCliente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(PainelButao, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(PainelPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(PainelCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(PainelButao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-678)/2, (screenSize.height-474)/2, 678, 474);
    }// </editor-fold>//GEN-END:initComponents

    private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarActionPerformed
        try {
            listarClientes();
            resetaEstados();
            emPesquisa.mudaParaEstado();
        } catch (BuscaException ex) {
            Logger.getLogger(ClienteForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException e) {
            MessageUtil.errorMessage(this, "Ocorreu um erro ao pesquisar");
        }
    }//GEN-LAST:event_btnPesquisarActionPerformed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        Validador validador = new ClienteValidador();
        try {
            if (validador.validar(getMapaDeAtributos())) {
                preencherClienteComCampos();
                if (emAdicao.isEstadoAtual()) {
                    if (validaCpf(txtCpf.getText())) {
                        clienteDao.criar(cliente);
                    } else {
                        throw new BuscaException();
                    }
                } else if (emEdicao.isEstadoAtual()) {
                    clienteDao.atualizar(cliente);
                }
                resetaEstados();
                inicial.mudaParaEstado();
                model.limpar();
            } else {
                StringBuilder sb = new StringBuilder("Foram encontrados os seguintes erros:");

                List<String> erros = validador.getErros();
                for (String erro : erros) {
                    sb.append("\n - " + erro);
                }
                MessageUtil.errorMessage(this, sb.toString());
            }
        } catch (BuscaException e) {
            MessageUtil.errorMessage(this, "CPF já cadastrado");
        } catch (Exception ex) {
            MessageUtil.errorMessage(this, "Ocorreu um erro ao salvar o cliente: " + ex.getMessage());
        }


    }//GEN-LAST:event_btnSalvarActionPerformed

    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        cliente = new Cliente();
        resetaEstados();
        emAdicao.mudaParaEstado();
    }//GEN-LAST:event_btnNovoActionPerformed

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnSairActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        try {
            int resposta = JOptionPane.showConfirmDialog(this, "Deseja realmente excluir este cliente?",
                    "Confirmação", JOptionPane.YES_NO_OPTION);

            if (resposta == JOptionPane.YES_NO_OPTION) {
                clienteDao.deletar(cliente);
                listarClientes();
                resetaEstados();
                inicial.mudaParaEstado();
                model.limpar();
            }
        } catch (Exception ex) {
            MessageUtil.errorMessage(this, "Ocorreu um erro ao excluir o cliente: " + ex.getMessage());
        }

}//GEN-LAST:event_btnExcluirActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        resetaEstados();
        inicial.mudaParaEstado();
        model.limpar();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void tabelaClientesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaClientesMouseClicked
        int linha = tabelaClientes.getSelectedRow();

        if (linha != -1) {
            cliente = model.getCliente(linha);
            preencheCamposComCliente();
            resetaEstados();
            emEdicao.mudaParaEstado();
        }        // TODO add your handling code here:
    }//GEN-LAST:event_tabelaClientesMouseClicked

    private void txtClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtClienteActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtClienteActionPerformed

    private void txtNascimentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNascimentoActionPerformed
    }//GEN-LAST:event_txtNascimentoActionPerformed

    private void txtNascimentoPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_txtNascimentoPropertyChange
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNascimentoPropertyChange
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel PainelButao;
    private javax.swing.JPanel PainelCliente;
    private javax.swing.JPanel PainelPesquisar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnPesquisar;
    private javax.swing.JButton btnSair;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblMensagem;
    private javax.swing.JTable tabelaClientes;
    private javax.swing.JTextField txtCliente;
    private javax.swing.JFormattedTextField txtCpf;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtEndereco;
    private javax.swing.JTextField txtId;
    private javax.swing.JFormattedTextField txtNascimento;
    private javax.swing.JTextField txtPesquisar;
    // End of variables declaration//GEN-END:variables
}
